import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  NavBar,
  Swiper,
  Image,
  Divider,
  Button,
  Stepper,
  Toast,
  Dialog,
  Space,
  Tag,
  Tabs
} from 'antd-mobile';
import {
  ShopbagOutline,
  StarOutline,
  StarFill,
  HeartOutline,
  SetOutline
} from 'antd-mobile-icons';
import { getProductPlaceholder } from '../../utils/imageUtils';
import './ProductDetail.css';
import { useRequest } from 'ahooks';
import { getProductDetail, getProductsDetail, addFavorite, removeFavorite, checkFavorite } from '../../api/store';
// 商品详情页面
const ProductDetail = () => {
  const navigate = useNavigate();
  const { productId } = useParams();
  const [product, setProduct] = useState(null);
  const [count, setCount] = useState(1);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('detail');
  const [isFavorite, setIsFavorite] = useState(false);
  const { runAsync: fetchProductDetail } = useRequest(getProductDetail, { manual: true });

  // 获取商品详情
  useEffect(() => {
    const loadProductDetail = async () => {
      setLoading(true);
      try {
        const productData = await fetchProductDetail({ params: { id: productId } });
        setProduct(productData);
        
        // 检查是否已收藏
        checkProductFavorite(productId);
      } catch (error) {
        console.error('获取商品详情失败:', error);
        Toast.show({
          icon: 'fail',
          content: '获取商品详情失败',
        });
      }
      setLoading(false);
    };

    loadProductDetail();
  }, [productId, fetchProductDetail]);
  
  // 检查商品是否已收藏
  const checkProductFavorite = async (productId) => {
    try {
      const result = await checkFavorite(productId);
      setIsFavorite(result.isFavorite);
    } catch (error) {
      console.error('检查收藏状态失败:', error);
    }
  };

  // 返回上一页
  const back = () => {
    navigate(-1);
  };

  // 添加到购物车
  const addToCart = () => {
    Toast.show({
      icon: 'success',
      content: '已添加到购物车',
    });

    // 获取购物车数据
    const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]');

    // 检查商品是否已在购物车中
    const existingItemIndex = cartItems.findIndex(item => item.id === product.id);

    if (existingItemIndex !== -1) {
      // 如果已存在，更新数量
      cartItems[existingItemIndex].quantity += count;
    } else {
      // 如果不存在，添加新商品
      cartItems.push({
        id: product.id,
        name: product.name,
        price: product.price,
        image: product.images[0],
        quantity: count,
        checked: true
      });
    }

    // 保存到本地存储
    localStorage.setItem('cartItems', JSON.stringify(cartItems));
  };

  // 立即购买
  const buyNow = () => {
    // 创建订单数据
    const orderItem = {
      id: product.id,
      name: product.name,
      price: product.price,
      image: product.images[0],
      quantity: count
    };

    // 保存订单项到本地存储
    localStorage.setItem('tempOrderItems', JSON.stringify([orderItem]));

    // 跳转到订单创建页面
    navigate('/order/create');
  };

  // 前往购物车
  const goToCart = () => {
    navigate('/cart');
  };

  // 收藏/取消收藏商品
  const toggleFavorite = async () => {
    try {
      if (isFavorite) {
        // 取消收藏
        const result = await removeFavorite({ productId });
        if (result.success) {
          setIsFavorite(false);
          Toast.show({
            icon: 'success',
            content: '已取消收藏',
          });
        }
      } else {
        // 添加收藏
        const result = await addFavorite({ productId });
        if (result.success) {
          setIsFavorite(true);
          Toast.show({
            icon: 'success',
            content: '已收藏',
          });
        } else {
          Toast.show({
            content: result.message || '收藏失败',
          });
        }
      }
    } catch (error) {
      console.error('收藏操作失败:', error);
      Toast.show({
        icon: 'fail',
        content: '操作失败，请重试',
      });
    }
  };

  // 切换标签页
  const handleTabChange = (key) => {
    setActiveTab(key);
  };

  if (loading || !product) {
    return (
      <div className="loading-container">
        <div className="loading-spinner">加载中...</div>
      </div>
    );
  }

  return (
    <div className="product-detail-container">
      {/* 导航栏 */}
      <NavBar onBack={back}>商品详情</NavBar>

      {/* 商品图片轮播 */}
      <Swiper autoplay loop className="product-swiper">
        {product.images.map((image, index) => (
          <Swiper.Item key={index}>
            <div className="product-image">
              <Image src={image} fit='cover' />
            </div>
          </Swiper.Item>
        ))}
      </Swiper>

      {/* 商品基本信息 */}
      <div className="product-info-section">
        <div className="product-price-section">
          <span className="product-price">¥{product.price.toFixed(2)}</span>
          {product.originalPrice && (
            <span className="product-original-price">¥{product.originalPrice.toFixed(2)}</span>
          )}
        </div>
        <div className="product-title">{product.name}</div>
        <div className="product-sub-info">
          <span>销量: {product.sales}</span>
          <span>库存: {product.stock}</span>
        </div>
      </div>

      {/* 商品数量选择 */}
      <div className="product-action-section">
        <div className="action-title">数量</div>
        <Stepper
          min={1}
          max={product.stock}
          value={count}
          onChange={setCount}
        />
      </div>

      {/* 商品详情/规格参数选项卡 */}
      <Tabs activeKey={activeTab} onChange={handleTabChange} className="product-tabs">
        <Tabs.Tab title="商品详情" key="detail" />
        <Tabs.Tab title="规格参数" key="specification" />
      </Tabs>

      {/* 详情内容 */}
      <div className="product-content">
        {activeTab === 'detail' ? (
          <div className="product-description">
            <p>{product.description}</p>
            <div className="detail-images">
              {(product.detailImages || product.images || []).map((image, index) => (
                <Image key={index} src={image} fit='cover' />
              ))}
            </div>
          </div>
        ) : (
          <div className="product-specifications">
            {(product.specifications || []).map((spec, index) => (
              <div key={index} className="spec-item">
                <span className="spec-key">{spec.key}</span>
                <span className="spec-value">{spec.value}</span>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 底部按钮区 - 完全重构 */}
      <div className="product-bottom-space"></div>
      <div className="product-fixed-buttons">
        <div className="product-action-icons">
          <div className="action-icon" onClick={goToCart}>
            <ShopbagOutline />
            <span>购物车</span>
          </div>
          <div className="action-icon" onClick={toggleFavorite}>
            {isFavorite ? <StarFill style={{ color: '#ff6f00' }} /> : <StarOutline />}
            <span>{isFavorite ? '已收藏' : '收藏'}</span>
          </div>
        </div>
        <div className="product-main-buttons">
          <button className="add-cart-btn" onClick={addToCart}>
            加入购物车
          </button>
          <button className="buy-now-btn" onClick={buyNow}>
            立即购买
          </button>
        </div>
      </div>
    </div>
  );
};

export default ProductDetail; 